import { queryMenuTree } from "@/api/system/menu";
import { queryRoleMenuIds, setAuthMenu } from "@/api/system/role";
import { Menu } from "@/types/system/menu";
import { Role } from "@/types/system/role";
import { message, Modal, Spin, Tree } from "antd";
import { useCallback, useEffect, useState } from "react";

interface Props {
  isModalOpen: boolean;
  roleId:string
  roleName:string
  close?: () => void;
  change?: () => void;
}
export default function AuthMenu(props: Props) {
  const [loading, setLoading] = useState(false);
  const [messageApi] = message.useMessage();
  const [menuIds, setMenuIds] = useState<Array<string>>([]);
  const [menuTree, setMenuTree] = useState<Menu[]>([]);
  /**
   * 回显接口
   * @param data
   */
  const getSelected = useCallback(async () => {
    if (!props.roleId) false;
    const res = await queryRoleMenuIds(props.roleId);
    if (res.code === 200) {
      const list = res.data || [];
      setMenuIds(list.map((item) => item.menuId));
    }
  }, [props.roleId]);
  /**
   * 获取菜单树
   */
  const getMenuList = async () => {
    setLoading(true);
    const res = await queryMenuTree();
    setLoading(false);
    if (res.code === 200) {
      const list = res.data || [];
      setMenuTree(list);
    }
  };
  /**
   * 修改接口
   * @param data
   */
  const authInf = async (data: Role.AuthMenu) => {
    try {
      setLoading(true);
      const res = await setAuthMenu(data);
      setLoading(true);
      if (res.code === 200) {
        props.close && props.close();
        props.change && props.change();
        messageApi.success("授权成功");
      }
    } catch (error) {
      console.log(error);

      setLoading(false);
    }
  };

  /**
   * 初始化
   */
  const initForm = useCallback(async () => {
    if (props.roleId) {
      await getSelected();
    }
    await getMenuList();
  }, [getSelected, props.roleId]);
  const handleOk = () => {
    const params = {
      menuIdList: menuIds,
      roleId: props.roleId,
    };
    authInf(params);
  };
  useEffect(() => {
    initForm();
  }, [initForm]);
  return (
    <Modal
      title={`${props.roleName}-授权菜单`}
      open={props.isModalOpen}
      onOk={handleOk}
      onCancel={() => props.close && props.close()}
    >
      <Spin spinning={loading}>
        <Tree
          checkable
          onCheck={(obj) => {   
            if(Array.isArray(obj)){
              setMenuIds(obj as string[]);
            }else{
              setMenuIds(obj.checked as string[]||[])
            }
           
          }}
          fieldNames={{title:'menuName',key:'id',children:'children'}}
          checkedKeys={menuIds}
          treeData={menuTree}
          checkStrictly={true}
        />
      </Spin>
    </Modal>
  );
}
